package handler

import (
	"boy-go/pkg/config"
	"boy-go/pkg/constants"
	"boy-go/pkg/redis"
	"github.com/gin-gonic/gin"
	"github.com/mojocn/base64Captcha"
	"log"
	"net/http"
)

func AddCaptchaRouter(gin *gin.Engine) {
	gin.GET("/captchaImage", getCaptchaImage)
}

// 验证码存储（简单示例，生产建议用 Redis）
var store = base64Captcha.DefaultMemStore

// 生成验证码[图片]
func getCaptchaImage(ctx *gin.Context) {

	if config.GetBoyGoConfig().CaptchaType == "math" {
		var driver = base64Captcha.DriverMath{
			Height:          60,
			Width:           180,
			NoiseCount:      1, //噪点数量
			ShowLineOptions: 1, //是否显示线条
		}
		captcha := base64Captcha.NewCaptcha(&driver, store)
		id, b64s, answer, err := captcha.Generate()
		log.Printf("id: %s, answer: %s", id, answer)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{"error": "生成验证码失败"})
			return
		}
		verifyKey := constants.CAPTCHA_CODE_KEY + id
		redis.SetValueForExpireTime(ctx, verifyKey, answer, 120)
		ctx.JSON(http.StatusOK, gin.H{
			"uuid": id,
			"img":  b64s,
		})
	} else {
		var driver = base64Captcha.DriverString{
			Height:          60,
			Width:           240,
			NoiseCount:      1,                                                              //噪点数量
			ShowLineOptions: 1,                                                              //是否显示线条
			Length:          4,                                                              //长度
			Source:          "0123456789qazwsxedcrfvtgbyhnujmikolpABCDEFGHJKLMNPQRSTUVWXYZ", //字符源
		}
		captcha := base64Captcha.NewCaptcha(&driver, store)
		id, b64s, answer, err := captcha.Generate()
		log.Printf("id: %s, answer: %s", id, answer)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{"error": "生成验证码失败"})
			return
		}
		verifyKey := constants.CAPTCHA_CODE_KEY + id
		redis.SetValueForExpireTime(ctx, verifyKey, answer, 120)
		ctx.JSON(http.StatusOK, gin.H{
			"uuid": id,
			"img":  b64s,
		})
	}

}
